package device

import (
	"goskeleton/app/global/variable"
	"goskeleton/app/model"
	"goskeleton/app/utils/response"
	"net/http"

	"goskeleton/app/global/consts"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Device struct{}

// List 获取设备列表
func (d *Device) List(c *gin.Context) {
	var devices []model.Device
	prefix := consts.ValidatorPrefix

	// 从上下文中获取验证过的数据
	page := int(c.GetFloat64(prefix + "page"))
	pageSize := int(c.GetFloat64(prefix + "page_size"))
	keyword := c.GetString(prefix + "keyword")
	platform := int16(c.GetFloat64(prefix + "platform"))

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 构建查询
	query := variable.GormDbMysql.Model(&model.Device{}).Where("is_deleted = ?", 0)

	// 添加名称模糊查询
	if keyword != "" {
		query = query.Where("name LIKE ?", "%"+keyword+"%")
	}

	// 添加平台筛选
	if platform != 0 {
		query = query.Where("platform = ?", platform)
	}

	// 获取总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		response.Fail(c, http.StatusInternalServerError, "获取设备总数失败："+err.Error(), nil)
		return
	}

	// 获取分页数据
	result := query.Offset(offset).Limit(pageSize).Find(&devices)
	if result.Error != nil {
		response.Fail(c, http.StatusInternalServerError, "获取设备列表失败："+result.Error.Error(), nil)
		return
	}

	// 构建响应数据
	responseData := gin.H{
		"list":      devices,
		"total":     total,
		"page":      page,
		"page_size": pageSize,
	}

	response.Success(c, "获取设备列表成功", responseData)
}

// Create 创建设备
func (d *Device) Create(c *gin.Context) {
	var device model.Device
	prefix := consts.ValidatorPrefix

	// 从上下文中获取验证过的数据
	device.Cpu = c.GetString(prefix + "cpu")
	device.ImageUrl = c.GetString(prefix + "image_url")
	device.Manufacturer = c.GetString(prefix + "manufacturer")
	device.ManSize = uint(c.GetFloat64(prefix + "man_size"))
	device.Model = c.GetString(prefix + "model")
	device.Name = c.GetString(prefix + "name")
	device.Password = c.GetString(prefix + "password")
	device.Platform = int16(c.GetFloat64(prefix + "platform"))
	device.Size = c.GetString(prefix + "size")
	device.UdId = c.GetString(prefix + "ud_id")
	device.Version = c.GetString(prefix + "version")
	device.NickName = c.GetString(prefix + "nick_name")
	device.IsHm = int16(c.GetFloat64(prefix + "is_hm"))
	device.Qrcode = c.GetString(prefix + "qrcode")
	device.IsShow = int8(c.GetFloat64(prefix + "is_show"))
	device.Orders = int(c.GetFloat64(prefix + "orders"))

	result := variable.GormDbMysql.Create(&device)
	if result.Error != nil {
		response.Fail(c, http.StatusInternalServerError, "创建设备失败："+result.Error.Error(), nil)
		return
	}
	response.Success(c, "创建设备成功", device)
}

// Update 更新设备
func (d *Device) Update(c *gin.Context) {
	var device model.Device
	prefix := consts.ValidatorPrefix

	// 从上下文中获取验证过的数据
	id := int64(c.GetFloat64(prefix + "id"))

	// 先检查设备是否存在且未删除
	var count int64
	result := variable.GormDbMysql.Model(&model.Device{}).Where("id = ? AND is_deleted = ?", id, 0).Count(&count)
	if result.Error != nil {
		response.Fail(c, http.StatusInternalServerError, "查询设备失败："+result.Error.Error(), nil)
		return
	}
	if count == 0 {
		response.Fail(c, http.StatusNotFound, "设备不存在或已被删除", nil)
		return
	}

	// 更新设备数据
	device.Id = id
	device.Cpu = c.GetString(prefix + "cpu")
	device.ImageUrl = c.GetString(prefix + "image_url")
	device.Manufacturer = c.GetString(prefix + "manufacturer")
	device.ManSize = uint(c.GetFloat64(prefix + "man_size"))
	device.Model = c.GetString(prefix + "model")
	device.Name = c.GetString(prefix + "name")
	device.Password = c.GetString(prefix + "password")
	device.Platform = int16(c.GetFloat64(prefix + "platform"))
	device.Size = c.GetString(prefix + "size")
	device.UdId = c.GetString(prefix + "ud_id")
	device.Version = c.GetString(prefix + "version")
	device.NickName = c.GetString(prefix + "nick_name")
	device.IsHm = int16(c.GetFloat64(prefix + "is_hm"))
	device.Qrcode = c.GetString(prefix + "qrcode")
	device.IsShow = int8(c.GetFloat64(prefix + "is_show"))
	device.Orders = int(c.GetFloat64(prefix + "orders"))

	result = variable.GormDbMysql.Save(&device)
	if result.Error != nil {
		response.Fail(c, http.StatusInternalServerError, "更新设备失败："+result.Error.Error(), nil)
		return
	}
	response.Success(c, "更新设备成功", device)
}

// Delete 删除设备（逻辑删除）
func (d *Device) Delete(c *gin.Context) {
	prefix := consts.ValidatorPrefix

	// 从上下文中获取验证过的数据
	id := int64(c.GetFloat64(prefix + "id"))

	// 执行逻辑删除，只更新 is_deleted 字段
	result := variable.GormDbMysql.Model(&model.Device{}).Where("id = ?", id).Update("is_deleted", 1)
	if result.Error != nil {
		response.Fail(c, http.StatusInternalServerError, "删除设备失败："+result.Error.Error(), nil)
		return
	}

	// 检查是否找到并更新了记录
	if result.RowsAffected == 0 {
		response.Fail(c, http.StatusNotFound, "设备不存在", nil)
		return
	}

	response.Success(c, "删除设备成功", nil)
}

// Detail 获取设备详情
func (d *Device) Detail(c *gin.Context) {
	var device model.Device
	prefix := consts.ValidatorPrefix

	// 从上下文中获取验证过的数据
	id := int64(c.GetFloat64(prefix + "id"))
	if id == 0 {
		response.Fail(c, http.StatusBadRequest, "无效的设备ID", nil)
		return
	}

	// 查询设备，确保ID存在且未删除
	result := variable.GormDbMysql.Debug().Where("id = ? AND is_deleted = ?", id, 0).First(&device)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			response.Fail(c, http.StatusNotFound, "设备不存在或已被删除", nil)
		} else {
			response.Fail(c, http.StatusInternalServerError, "获取设备详情失败："+result.Error.Error(), nil)
		}
		return
	}

	// 再次确认设备状态
	if device.Id == 0 || device.IsDeleted == 1 {
		response.Fail(c, http.StatusNotFound, "设备不存在或已被删除", nil)
		return
	}

	response.Success(c, "获取设备详情成功", device)
}
